/*
* @Author: steven.wang
* @Date:   2019-01-09 17:00:18
* @Last Modified by:   steven.wang
* @Last Modified time: 2019-05-08 17:38:21
*/
const jwt = require('jsonwebtoken');
const md5 = require('md5');
const secret = require('../config').secret;
const UserModel = require('../models/user');
const getJwtPayload = require('../utils/tools').getJwtPayload;
const jsonSendFormat = require('../utils/tools').jsonSendFormat;
/**
 * 登录
 * @author steven.wang
 * @DateTime 2019-02-27T10:10:25+0800
 */
exports.signin = async function(req, res) {
	const {username = '', password = ''} = req.body;
	if (username == '' || password == '') {
		return res.json(jsonSendFormat(500, '账号或密码错误'));
	}
	const user = await UserModel.findUserByUsername({
		username: username
	});
	if (user && user.length > 0) {
		if (user[0].password == md5(password)) {
			const {
				id, username
			}  = user[0];
			const token = jwt.sign({
				id: id,
				username: username
			}, secret, {
				expiresIn: Math.floor(Date.now()/1000) + 24 * 60 * 60 * 7 // 一周
			})
			res.json(jsonSendFormat(200, {
				userId: id,
				username: username,
				token: token
			}));
		} else {
			res.json(jsonSendFormat(500, '密码错误'));
		}
	} else {
		res.json(jsonSendFormat(500, '账号或密码错误'));
	}
}
/**
 * 注册
 * @author steven.wang
 * @DateTime 2019-02-27T10:10:39+0800
 */
exports.signup = function(req, res) {
	res.json('signup controller');
	// let photos = await PhotoModel.findPhotos(req.query);
	// let count = await PhotoModel.countPhoto(req.query);
	// res.json({
	// 	success: true,
	// 	msg: '',
	// 	data: {
	// 		page: req.query.page || 1,
	// 		pageSize: req.query.pageSize || 10,
	// 		total: count[0]['count(*)'],
	// 		list: photos
	// 	}
	// })
}
/**
 * 退出登录
 * @author steven.wang
 * @DateTime 2019-02-27T10:10:46+0800
 */
exports.signout = function(req, res) {
	res.json('signout controller');
}
/**
 * 查询用户
 * @author steven.wang
 * @DateTime 2019-02-27T10:10:46+0800
 */
exports.getUserInfo = async function(req, res) {
	let data = await getJwtPayload(req.headers.authorization.split(' ')[1]);
	let user = await UserModel.findUserByUsername({
		username: data.username
	});
	if (user && user.length > 0) {
		user[0].roles = ['admin']
		res.json({
			code: 200,
			msg: '查询成功',
			data: user[0]
		});
	} else {
		res.json({
			success: false,
			msg: '没有查到该用户信息'
		})
	}
}